package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.annotation.JsonObject;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.CeAgentAccountDao;
import com.jy.admin.db.dao.CeCommentPushLogDao;
import com.jy.admin.db.dao.CeMerchantDao;
import com.jy.admin.db.dao.CeOrdersDetailDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.jy.bo.common.conf.util.HttpUtil;
import com.qianli.cashmama.trade.common.utils.HttpUtils;
import com.robert.vesta.util.IdUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class RupeeSpreeService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RupeeSpreeService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("rupeespree", this);
        BaseJobHandler.merchantAndServiceMap.put("winterloan", this);
    }


    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            Map<String, String> headers = getHeaders(agentAccount);
            headers.remove("token");
            String url = merchant.getApiDomain() + "/india-system-api/sys/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            JSONObject params = new JSONObject();
            params.put("username", agentAccount.getAccount());
            params.put("password", agentAccount.getPassword());
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            if (JsonIterator.deserialize(result).get("code").toInt() == 0) {
                LOGGER.error("== 自动登录成功==，data:{}", JsonIterator.deserialize(result).get("result").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("token", JsonIterator.deserialize(result).get("result").get("token").toString());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return true;
            } else {
                LOGGER.info("== 自动登录失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
            }
        } else {
            LOGGER.info("== 未开启自动登录 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            boolean isLogin = autoLogin(agentAccount);
            if (!isLogin) {
                return false;
            }
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/india-system-api/reminder/cases/case/queryMyCase?page=1&pageSize=50&orderByField=&order=&keyword=&caseStatus=&touchStatus=&isFollowed=&overdueDaysMin=&overdueDaysMax=&daysFromLastFollowTimeMin=&daysFromLastFollowTimeMax=&financeOverdueStart=&financeOverdueEnd=&repayWilling=";
        LOGGER.info("== 开始请求个人信息 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPageSSL(url, params, headers);
        LOGGER.info("== 请求个人信息结果 ==,result:{}", result);
        Any code = JsonIterator.deserialize(result).get("code");
        if (code.toInt() != 0) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return autoLogin(agentAccount);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== RupeeSpreeService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        String url = merchant.getApiDomain() + "/india-system-api/reminder/cases/case/queryMyCase?page=1&pageSize=500&orderByField=&order=&keyword=&caseStatus=&touchStatus=&isFollowed=&overdueDaysMin=&overdueDaysMax=&daysFromLastFollowTimeMin=&daysFromLastFollowTimeMax=&financeOverdueStart=&financeOverdueEnd=";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);


        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPageSSL(url, params, headers);
        Any resultJson = JsonIterator.deserialize(result);

        if (resultJson.get("code").toInt() != 0) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        if (resultJson.get("result") == null) {
            LOGGER.info("== 请求接口数据为空 ==，account:{}", agentAccount.getAccount());
            return;
        }
        List<Any> resultsList = resultJson.get("result").get("records").asList();
        LOGGER.info("== 获取订单列表 ==，account:{},size:{}", agentAccount.getAccount(), resultsList.size());


        if (CollectionUtils.isEmpty(resultsList)) {
            LOGGER.info("== 请求接口数据为空  item 为空==，account:{}", agentAccount.getAccount());
            return;
        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());

        //对比订单数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("caseNo").toString();
                    String collectionNo = IdUtils.genId() + "";
                    if (agentAccount.getStage().contains("d")) {
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(collectionNo);
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        CeOrdersEntity OneByOrderNo = ordersDao.getOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                        if (OneByOrderNo == null) {
                            LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                            CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                    .setAgentCode(agentAccount.getAgentCode())
                                    .setMerchantCode(agentAccount.getMerchantCode())
                                    .setOrderNo(orderNo)
                                    .setOrderInfo(item.toString())
                                    .setStatus(OrderStatusEnum.active.getStatus())
                                    .setCreateDt(new Date())
                                    .setCollectionNo(collectionNo);
                            ordersDao.insert(ceOrdersEntity);
                        } else {
                            LOGGER.info("== 列表为空,订单已存在,更新参数 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                            OneByOrderNo.setCollectionNo(collectionNo);
                            OneByOrderNo.setCreateDt(new Date());
                            OneByOrderNo.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                            OneByOrderNo.setOrderInfo(JsonStream.serialize(item));
                            ordersDao.insert(OneByOrderNo);

                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("caseNo").toString(), e);
                }
            });
        } else {
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("caseNo").toString();
                    String collectionNo = IdUtils.genId() + "";
                    CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (OneByOrderNo == null) {
                        LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(collectionNo);
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("== 订单已存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);

                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });


            activeOrders.forEach(item -> {
                try {
                    String id = JsonIterator.deserialize(item.getOrderInfo()).get("caseNo").toString();
                    boolean hasOrder = false;
                    for (int i = 0; i < resultsList.size(); i++) {
                        Any child = resultsList.get(i);
                        String orderNo = child.get("caseNo").toString();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                            hasOrder = true;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 更新数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }

        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();

                HashMap<String, String> params = Maps.newHashMap();
                String orderInfo = order.getOrderInfo();
                String orderId = JsonIterator.deserialize(orderInfo).get("id").toString();

                String orderDetailUrl = merchant.getApiDomain() + "/india-system-api/reminder/cases/case/find/" + orderId;
                String orderDetailInfo = HttpUtil.getPageSSL(orderDetailUrl, params, headers);

                if (StringUtils.isEmpty(orderDetailInfo)) {
                    LOGGER.info("== 获取订单详情失败 ==,orderNo:{},agentCode:{}", orderId, agentAccount.getAgentCode());
                    return;
                }

                if (JsonIterator.deserialize(orderDetailInfo).get("code").toInt() != 0) {
                    LOGGER.info("== 获取订单详情失败 ==,orderNo:{},agentCode:{}", orderId, agentAccount.getAgentCode());
                    return;
                }
                Any data = JsonIterator.deserialize(orderDetailInfo).get("result");

                if (!data.toString().equals("")) {
                    infoMap.put("repaymentInfo", data.toString());
                    LOGGER.info("== 获取成功 repaymentInfo==");
                    String remainMoney = data.get("financeNeedRepayTotal").toString();
                    updateRemainMoney(order.getCollectionNo(), remainMoney);
                }


                if (!hasDetailData) {
                    String imageUrl = merchant.getApiDomain() + "/india-system-api/getruppe-risk-admin/risk/identityInfo/queryIdentityInfo?order_no=" + data.get("bidNo").toString();
                    String imageInfoResult = HttpUtil.getPageSSL(imageUrl, params, headers);
                    Any imageInfo = JsonIterator.deserialize(imageInfoResult).get("result");
                    String pan_code = imageInfo.get("pan_code").toString();
                    String aadhaar_no = imageInfo.get("aadhaar_no").toString();
                    List<String> images = Lists.newArrayList();
                    if (!imageInfo.get("aadhhar_front_url").toString().equals("")) {
                        images.add(imageInfo.get("aadhhar_front_url").toString());
                    }
                    if (!imageInfo.get("aadhhar_back_url").toString().equals("")) {
                        images.add(imageInfo.get("aadhhar_back_url").toString());
                    }
                    if (!imageInfo.get("pan_front_url").toString().equals("")) {
                        images.add(imageInfo.get("pan_front_url").toString());
                    }
                    if (!imageInfo.get("ocr_url").toString().equals("")) {
                        images.add(imageInfo.get("ocr_url").toString());
                    }
                    infoMap.put("images", JsonStream.serialize(images));
                    LOGGER.info("== 获取成功 images==");

                    CeOrdersDetailEntity baseInfoDetails = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetails == null) {
                        JSONObject map = JSONObject.parseObject(data.toString());
                        map.put("panCode",pan_code);
                        map.put("aadhaarNo",aadhaar_no);
                        infoMap.put("baseInfo", map.toString());
                        LOGGER.info("== 获取成功 baseInfo==");
                    } else {
                        baseInfoDetails.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetails);
                    }


                    CeOrdersDetailEntity contactInfoDetails = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetails == null) {

                        String contactsUrl = merchant.getApiDomain() + "/india-system-api/reminder/cases/caseEmergencyContact/queryByCaseId?caseId=" + orderId;
                        String contactsResult = HttpUtil.getPageSSL(contactsUrl, params, headers);
                        List<Any> contactsList = JsonIterator.deserialize(contactsResult).get("result").asList();
                        JSONArray contactsInfo = new JSONArray();
                        for (Any vo : contactsList) {
                            JSONObject j1 = new JSONObject();
                            j1.put("name", vo.get("contactName").toString());
                            if (!vo.get("telephone").toString().equals("")) {
                                j1.put("phone", vo.get("telephone").toString());
                                contactsInfo.add(j1);
                            }
                        }
                        infoMap.put("contactInfo", contactsInfo.toString());
                    } else {
                        contactInfoDetails.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetails);
                    }
                    CeOrdersDetailEntity contactUrlDetails = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetails == null) {
                        List<Any> contactList;
                        try {
                            String contactsUrl = merchant.getApiDomain() + "/india-system-api/reminder/cases/caseDetail/getContacts?caseId=" + orderId + "&classifyList=";
                            String contactsResult = HttpUtil.getPageSSL(contactsUrl, params, headers);
                            contactList = JsonIterator.deserialize(contactsResult).get("result").asList();
                            JSONArray contacts = new JSONArray();
                            for (Any vo : contactList) {
                                JSONObject j1 = new JSONObject();
                                j1.put("name", vo.get("contactName").toString());
                                if (!vo.get("telephone").toString().equals("")) {
                                    j1.put("phone", vo.get("telephone").toString());
                                    contacts.add(j1);
                                }
                            }
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", contacts);

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);


                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetails.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetails);
                    }


                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String appName = agentAccount.getAppName() + "[" + orderInfo.get("productName").toString() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                String borrowCapital = repaymentInfo.get("confirmAmount").toString();
                String actualAmount = repaymentInfo.get("confirmAmount").toString();
                String overdueDays = repaymentInfo.get("financeOverdueDays").toString();
                String serviceFee = new BigDecimal(repaymentInfo.get("needRepayGstAmount").toString()).add(new BigDecimal(repaymentInfo.get("leftNeedRepayInterest").toString())).toString();
                String remainMoney = repaymentInfo.get("financeNeedRepayTotal").toString();
                String lateFee = repaymentInfo.get("needRepayOverdueFeeAmount").toString();
                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(actualAmount), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String totalAmount = repaymentInfo.get("financeNeedRepayTotal").toString();
                Any inForceDate = repaymentInfo.get("financeLoanTime");
                Any dueDate = repaymentInfo.get("repayTime");
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest(repaymentInfo.get("leftNeedRepayInterest").toString())
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(repaymentInfo.get("bidTotalReceivedAmount").toString())
                        .setReceivedDate(inForceDate.toString())
                        .setRepaymentDate(dueDate.toString())
                        .setRemainMoney(remainMoney)
                        .setTotalMoney(totalAmount);

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = personalInfoJson.get("aadhaarNo").toString();
                String pancardNo = personalInfoJson.get("panCode").toString();
                String email = "no";
                String mobile = orderInfo.get("borrowerTel").toString();
                String name = personalInfoJson.get("borrowerUserName").toString();
                String state = "no";
                int gender = 0;
                String address = personalInfoJson.get("residenceAddress").toString();
                String pinCode = "no";
                String city = personalInfoJson.get("borrowerArea").toString();

                int age = personalInfoJson.get("age").toInt();
                String birthDay = Integer.parseInt(DateUtil.getYear()) - age + "-" + DateUtil.getMonth() + "-" + DateUtil.getDay();

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() == 1) {
                    parentName = name;
                    parentPhone = mobile;
                    friendName = contactInfoJson.get(0).get("name").toString();
                    friendMobile = contactInfoJson.get(0).get("phone").toString();
                } else if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(contactInfoJson.size() - 1).get("name").toString();
                    friendMobile = contactInfoJson.get(contactInfoJson.size() - 1).get("phone").toString();
                }


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(0)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        Map<String, String> params = Maps.newHashMap();


        waitingPaidCheckOrders.forEach(order -> {
            String orderInfo = order.getOrderInfo();
            String orderId = JsonIterator.deserialize(orderInfo).get("id").toString();
            String url = merchant.getApiDomain() + "/india-system-api/reminder/cases/caseSettled/find/" + orderId;
            LOGGER.info("== RupeeSpree开始请求订单详情 ==,url:{}", url);
            String result = HttpUtil.getPageSSL(url, params, headers);
            LOGGER.info("== RupeeSpree请求订单详情 ==,result:{}", result);
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() != 0 && resultJson.get("code").toInt() != 400) {
                LOGGER.info("== 订单详情异常 ==");
                return;
            }
            if (resultJson.get("result").toString().equals("null")) {
                LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
                order.setStatus(OrderStatusEnum.removed.getStatus());
                order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                ordersDao.updateByPrimaryKey(order);
                return;
            }
            Any currentOrder = resultJson.get("result");
            if (currentOrder.get("caseStatus").toString().equals("5")) {//repayState:3为已还款，0为未还款
                LOGGER.info("== 订单已还款 ==,OrderNo:{},repayState:{}", order.getOrderNo(), currentOrder.get("caseStatus").toString());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
                return;
            }

            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = repaymentInfo.get("bidTotalReceivedAmount").toString().equals("") ? "0" : repaymentInfo.get("bidTotalReceivedAmount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("realRepayAmount").toString().equals("") ? "0" : repaymentInfo.get("realRepayAmount").toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        RupeeSpreeCollectionTagEnum currentTag = RupeeSpreeCollectionTagEnum.RNR_V2;

        for (RupeeSpreeCollectionTagEnum e : RupeeSpreeCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            params.put("callRecordId", "");
            params.put("callVender", "");
            params.put("caseId", orderInfo.get("id").toString());
            params.put("collectionType", 1);
            params.put("collectionContent", "");
            params.put("contactName", orderInfo.get("borrowerUserName").toString());
            params.put("isPromisePay", 0);
            params.put("promisePayTime", "");
            params.put("nextCollectionTime", "");
            params.put("promiseRepayAmount", 0);
            params.put("telephone", orderInfo.get("borrowerTel").toString());
            params.put("collectionCode", "M1");
            params.put("touchStatus", currentTag.getState());
            params.put("touchType", 1);

            LOGGER.info("== cashhost 开始同步催记到甲方 ==,params:{}", JsonStream.serialize(params));
            String result = HttpUtil.postPageBody(ceMerchantEntity.getApiDomain() + "/india-system-api/reminder/cases/caseCollectionRecord/add", headers, params.toString());
            LOGGER.info("== cashhost 开始同步催记到甲方 ==,res:{}", result);

            if ("0".equals(JsonIterator.deserialize(result).get("code").toString())) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        String link = "No Link";
        return link;
    }


    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());


        String renewLink = "No Link";
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }


    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();

        String orderInfo = ordersEntity.getOrderInfo();
        String orderId = JsonIterator.deserialize(orderInfo).get("id").toString();
        String url = merchant.getApiDomain() + "/india-system-api/reminder/cases/caseSettled/find/" + orderId;
        LOGGER.info("== 开始请求订单详情 ==,url:{}", url);
        String result = HttpUtil.getPageSSL(url, params, headers);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() != 0 && resultJson.get("code").toInt() != 400) {
            LOGGER.info("== 订单详情异常 ==");
            return "no order found";
        }
        Any currentOrder = resultJson.get("result");
        if (currentOrder.get("caseStatus").toString().equals("5")) {//repayState:3为已还款，0为未还款
            LOGGER.info("== 订单已还款 ==,OrderNo:{},repayState:{}", ordersEntity.getOrderNo(), currentOrder.get("caseStatus").toString());
            if (!ordersEntity.getSyncStatus().equals(OrderSyncStatusEnum.pay_update_success.getStatus())) {
                ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
            }
            ordersEntity.setStatus(OrderStatusEnum.paid_update.getStatus());
            ordersDao.updateByPrimaryKey(ordersEntity);
            return "paid already!";
        }
        return "no paid";
    }

    public static void main(String[] args) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("lang", "en-us");
        headers.put("customer", "3XELTZUO");
        headers.put("auth", "80FDA07DEAA5449A80204D7D3C1674EA-86400");
        headers.put("Referer", "https://client.cooindfodghr.com/cm-dunning-case-list");
        Map<String, String> params = new HashMap<>();
        String body = "{\"query\":{\"pageNo\":1,\"pageSize\":100,\"orderQuery\":{\"userInfo\":{}},\"status\":\"PENDING\",\"filterAllCase\":true}}";
        String s = com.qianli.cashmama.trade.common.utils.HttpUtil.postPageBodyByHttps("https://client.cooindfodghr.com/api/cm_dunning_case/page",
                headers,
                body
        );

        System.err.println(s);
    }

    public static void main1(String[] args) {

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"query\":{\"pageNo\":1,\"pageSize\":100,\"orderQuery\":{\"userInfo\":{}},\"status\":\"PENDING\",\"filterAllCase\":true}}");
        Request request = new Request.Builder()
                .url("https://client.cooindfodghr.com/api/cm_dunning_case/page")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("lang", "en-us")
                .addHeader("customer", "3XELTZUO")
                .addHeader("auth", "80FDA07DEAA5449A80204D7D3C1674EA-86400")
                .addHeader("Referer", "https://client.cooindfodghr.com/cm-dunning-case-list")
//                .addHeader("sec-ch-ua-mobile", "?0")
//                .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
//                .addHeader("sec-ch-ua-platform", "\"macOS\"")
//                .addHeader("sec-fetch-dest", "empty")
//                .addHeader("sec-fetch-mode", "cors")
//                .addHeader("sec-fetch-site", "same-origin")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String s = response.body().string();
            System.err.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
